package com.yequan.thread.base.callable;

import org.junit.Test;
import org.omg.CORBA.PUBLIC_MEMBER;

import java.util.concurrent.*;

/**
 * @author yq
 * @date 2020/08/14
 */
public class CallableDemo {

    @Test
    public void cancelTest() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> future = executor.submit(new Task());
        executor.shutdown();

        System.out.println("主线程执行任务");
        Thread.sleep(1000);
        if (!future.isCancelled()) {
            boolean cancel = future.cancel(true);
            System.out.println("取消子任务" + cancel);
        }
        //Future.get()会阻塞主线程
        if (!future.isCancelled()) {
            System.out.println(future.get());
        }
        System.out.println("所有任务结束");
    }

    @Test
    public void getTest() throws InterruptedException, ExecutionException, TimeoutException {
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> future = executor.submit(new Task());
        Integer result = future.get(1, TimeUnit.SECONDS);
        System.out.println("1秒内获得的结果为：" + result);
    }

    static class Task implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("子线程正在执行任务");
            Thread.sleep(3000);
            int sum = 0;
            for (int i = 0; i < 100; i++) {
                sum += i;
            }
            return sum;
        }
    }

}
